package com.dbg.ui;

import com.dbg.entity.Language;
import com.dbg.entity.ResultEntity;
import com.dbg.ui.animation.RotationImage;
import com.dbg.ui.table.model.SelectedTableModel;
import com.dbg.utils.FileUtils;
import com.dbg.utils.JSONUtils;
import com.dbg.utils.PDFUtils;
import com.formdev.flatlaf.FlatLightLaf;
import javax.swing.*;
import javax.swing.table.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.List;
import java.util.concurrent.ExecutionException;

public class MainUI {

    private String path = "";
    private String savePath = "";
    private String saveName = "";
    private String saveVersion = "";
    private JTextField name;
    private JTextField version;
    private JFrame frame;
    private JButton ok;
    private JWindow window = new JWindow();
    private RotationImage rotationPanel = new RotationImage();
    private final List<Language> languages = JSONUtils.languagesList;
    private SelectedTableModel tableModel = new SelectedTableModel(new ArrayList<Language>());

    private JTable table = new JTable();

    public MainUI() {
        // 设置外观
        try {
            UIManager.setLookAndFeel(new FlatLightLaf());
        } catch (Exception e) {
            e.printStackTrace();
        }

        // 创建框架
        frame = new JFrame("软件著作权代码文档生成器V1.0");
        frame.setSize(800, 560);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLayout(new BorderLayout());
        frame.setLocationRelativeTo(null);
        frame.setResizable(false);

        // 南边的JPanel，尺寸为800x50
        JPanel southPanel = new JPanel();
        southPanel.setPreferredSize(new Dimension(800, 50));
        southPanel.setBackground(Color.ORANGE); // 设置背景色以区分区域

        // 添加面板到框架中
        frame.add(northPanel(), BorderLayout.NORTH);
        frame.add(centerPanel(), BorderLayout.CENTER);
        frame.add(southPanel(), BorderLayout.SOUTH);

        frame.setVisible(true);
    }

    // 南区面板
    private JPanel southPanel() {
        JPanel southPanel = new JPanel(new GridLayout(1, 2));
        southPanel.setPreferredSize(new Dimension(800, 50));

        JButton genDoc = new JButton("生成文档");
        JButton cleanList = new JButton("清除语言");

        southPanel.add(genDoc);
        southPanel.add(cleanList);

        genDoc.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (MainUI.this.path.trim().isEmpty()) {
                    JOptionPane.showMessageDialog(
                            MainUI.this.frame,
                            "未选择源代码目录",
                            "警告",
                            JOptionPane.WARNING_MESSAGE
                    );
                } else if (tableModel.getLanguageList().size() == 0) {
                    JOptionPane.showMessageDialog(
                            MainUI.this.frame,
                            "未选择任何一种语言或框架",
                            "警告",
                            JOptionPane.WARNING_MESSAGE
                    );
                } else {
                    MainUI.this.selectSavePath();
                }
//                MainUI.this.selectSavePath();
            }
        });

        cleanList.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                tableModel.setLanguageList(new ArrayList<Language>());
                tableModel.updateData();
            }
        });

        return southPanel;
    }

    // 中区面板
    private JPanel centerPanel() {
        // 中间的JPanel，尺寸为800x50
        JPanel centerPanel = new JPanel(new BorderLayout());
        centerPanel.setPreferredSize(new Dimension(800, 320));
        centerPanel.setBackground(Color.CYAN); // 设置背景色以区分区域

        centerPanel.add(tableInit());

        return centerPanel;
    }

    // 北区面板
    private JPanel northPanel() {
        // 北边的JPanel，尺寸为800x50
        JPanel northPanel = new JPanel(new GridLayout(2, 1));
        northPanel.setPreferredSize(new Dimension(800, 100));
        northPanel.setBackground(Color.LIGHT_GRAY); // 设置背景色以区分区域

        // 文件选择器
        northPanel.add(selectPathPanel());

        // 第二行提示以及选择语言
        JPanel panelLower = new JPanel(new GridLayout(1, 2, 0, 0));
        panelLower.setPreferredSize(new Dimension(800, 50));
        northPanel.add(panelLower);
        panelLower.add(new JButton("选择语言的位序决定文档中各语言代码位置"));
        panelLower.add(languageSelector());

        return northPanel;
    }

    // 选择保存文件夹
    private void selectSavePath() {
        final JDialog dialog = new JDialog(frame, "选择保存路径", true);
        dialog.setSize(720, 184);
        dialog.setLayout(new BorderLayout());

        final JButton selectPath = new JButton("选择保存路径");
        if (!savePath.trim().isEmpty()) {
            selectPath.setText(savePath);
        }
        selectPath.setPreferredSize(new Dimension(720, 50));

        selectPath.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                JFileChooser chooser = new JFileChooser();
                chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                int returnValue = chooser.showOpenDialog(null);
                if (returnValue == JFileChooser.APPROVE_OPTION) {
                    File selectedFile = chooser.getSelectedFile();
                    MainUI.this.savePath = selectedFile.getAbsolutePath();
                    selectPath.setText(MainUI.this.savePath);
                }
            }
        });
        dialog.add(selectPath, BorderLayout.NORTH);
        dialog.setLocationRelativeTo(null);

        dialog.add(inputNameAndVersion(), BorderLayout.CENTER);

        // 确定生成文档
        ok = new JButton("确定生成文档");
        ok.setPreferredSize(new Dimension(720, 50));
        dialog.add(ok, BorderLayout.SOUTH);
        ok.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                if (MainUI.this.savePath.trim().isEmpty()) {
                    JOptionPane.showMessageDialog(
                            MainUI.this.frame,
                            "未选择文档保存目录",
                            "警告",
                            JOptionPane.WARNING_MESSAGE
                    );
                } else {
                    try {
                        genDocumentPDF();
                    } catch (IOException ex) {
                        // 找不到JSON文件
                        JOptionPane.showMessageDialog(
                                MainUI.this.frame,
                                "找不到JSON配置文件",
                                "错误",
                                JOptionPane.ERROR_MESSAGE
                        );
                    }
                    dialog.setVisible(false);
                }
//                try {
//                    genDocumentPDF();
//                } catch (IOException ex) {
//                    ex.printStackTrace();
//                }
            }
        });

        dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        dialog.setVisible(true);

    }

    // 输入项目名称、版本号
    private JPanel inputNameAndVersion() {
        // 输入项目名称、版本
        JPanel centerPanel = new JPanel(new GridLayout(1, 2));
        centerPanel.setPreferredSize(new Dimension(800, 50));

        name = new JTextField("输入项目名称");
        version = new JTextField("输入项目版本(1.0/V1.0)");

        if (!this.saveName.trim().isEmpty()) {
            name.setText(saveName);
        }

        if (!this.saveVersion.trim().isEmpty()) {
            version.setText(saveVersion);
        }

        centerPanel.add(name);
        centerPanel.add(version);

        name.addFocusListener(new FocusAdapter() {
            @Override
            public void focusGained(FocusEvent e) {
                if (name.getText().equals("输入项目名称")) {
                    name.setText("");
                }
            }
        });

        version.addFocusListener(new FocusAdapter() {
            @Override
            public void focusGained(FocusEvent e) {
                if (version.getText().equals("输入项目版本(1.0/V1.0)")) {
                    version.setText("");
                }
            }
        });

        return centerPanel;
    }

    // 生成文档最终执行函数
    private void genDocumentPDF() throws IOException {

        this.saveName = name.getText();
        this.saveVersion = version.getText();

        Set<String> languageSet = new HashSet<>();
        HashMap<String, Integer> sortRule = new HashMap<>();
        List<Language> languageList = tableModel.getLanguageList();
        for (int i = 0; i < languageList.size(); i++) {
            String fileName = languageList.get(i).getFileName();
            languageSet.add(fileName);
            sortRule.put(fileName, i + 1);
        }
        List<String> strings = FileUtils.iterationFile(path, languageSet, sortRule);
        processPDF(strings);
//        ResultEntity entity = PDFUtils.codeToPdf(strings, savePath, name.getText(), version.getText());
//        System.out.println(entity.isSUCCESS());
    }

    // 等待PDF文件处理
    private void processPDF(final List<String> strings) {
        // 创建SwingWorker进行后台处理
        //
        new SwingWorker<ResultEntity, Void>() {
            @Override
            protected ResultEntity doInBackground() throws Exception {
                MainUI.this.startRotate();
                return PDFUtils.codeToPdf(strings, savePath, MainUI.this.name.getText(), MainUI.this.version.getText());
            }

            @Override
            protected void done() {
                try {
                    ResultEntity entity = get();
                    if (entity.isSUCCESS()) {
                        MainUI.this.rotationPanel.stopRotation();
                        MainUI.this.window.setVisible(false);
                        JOptionPane.showMessageDialog(
                                MainUI.this.frame,
                                "生成文档成功, 共" + entity.getMessage("line") + "行代码",
                                "提示",
                                JOptionPane.INFORMATION_MESSAGE
                        );
                        String pdfPath = savePath + "\\" + name.getText() + version.getText() + "源程序.pdf";
                        File pdfFile = new File(pdfPath);
                        // 使用 Desktop 打开 PDF 文件
                        if (Desktop.isDesktopSupported()) {
                            try {
                                Desktop.getDesktop().open(pdfFile);
                            } catch (IOException e) {
                                MainUI.this.rotationPanel.stopRotation();
                                MainUI.this.window.setVisible(false);
                                JOptionPane.showMessageDialog(
                                        MainUI.this.frame,
                                        "无法打开文件: " + e.getMessage(),
                                        "错误",
                                        JOptionPane.ERROR_MESSAGE
                                );
                            }
                        } else {
                            JOptionPane.showMessageDialog(
                                    MainUI.this.frame,
                                    "不支持桌面操作",
                                    "错误",
                                    JOptionPane.ERROR_MESSAGE
                            );
                        }
                    } else if (entity.isERROR()) {
                        MainUI.this.rotationPanel.stopRotation();
                        MainUI.this.window.setVisible(false);
                        JOptionPane.showMessageDialog(
                                MainUI.this.frame,
                                "生成文档失败, 错误信息: " + entity.getMessage("msg") + "。请重试",
                                "错误",
                                JOptionPane.ERROR_MESSAGE
                        );
                    }
                } catch (InterruptedException | ExecutionException e) {
                    MainUI.this.rotationPanel.stopRotation();
                    MainUI.this.window.setVisible(false);
                    JOptionPane.showMessageDialog(
                            MainUI.this.frame,
                            "生成文档失败, 错误信息: " + e.getMessage(),
                            "错误",
                            JOptionPane.ERROR_MESSAGE
                    );
                }
            }
        }.execute();
    }

    // 开始动画旋转
    private void startRotate() {
        // 使用JWindow创建无边框窗体，并设置透明
        rotationPanel.setBackground(new Color(255, 255, 255, 0));
        window.add(rotationPanel);
        window.setSize(155, 210);
        window.setLocationRelativeTo(null); // 窗体居中
        // 设置背景为透明
        window.setBackground(new Color(0, 0, 0, 0));
        window.setVisible(true);
    }

    // 下拉列表
    private JComboBox<String> languageSelector() {
        final JComboBox<String> selector = new JComboBox<>();
        selector.setPreferredSize(new Dimension(180, 32));

        for (Language language : languages) {
            selector.addItem(language.getName());
        }

        selector.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int selectIndex = selector.getSelectedIndex();
                System.out.println(11111);
                if (selectIndex >= 0) {
                    Language language = languages.get(selectIndex);
                    boolean flag = true;
                    for (Language language1 : tableModel.getLanguageList()) {
                        if (language1.getId().equals(language.getId())) {
                            flag = false;
                            break;
                        }
                    }

                    if (flag) {
                        tableModel.addLanguage(language);
                        tableModel.updateData();
                    }
                }
            }
        });

        return selector;
    }

    // 选择文件夹
    private JButton selectPathPanel() {
        final JButton filePathBtn = new JButton("选择文件夹");
        filePathBtn.setPreferredSize(new Dimension(780, 32));

        // 按钮点击事件处理
        filePathBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JFileChooser chooser = new JFileChooser();
                chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                int returnValue = chooser.showOpenDialog(null);
                if (returnValue == JFileChooser.APPROVE_OPTION) {
                    File selectedFile = chooser.getSelectedFile();
                    MainUI.this.path = selectedFile.getAbsolutePath();
                    filePathBtn.setText(MainUI.this.path);
                }
            }
        });

        return filePathBtn;
    }

    // 表格初始化
    private JScrollPane tableInit() {
        tableModel = new SelectedTableModel(tableModel.getLanguageList());
        table = new JTable(tableModel);
        for (int i = 0; i < 7; i++) {
            TableColumn column = table.getColumnModel().getColumn(i);
            column.setPreferredWidth(110);
        }

        // 注册表格点击事件
        addTableMouseListener();

        DefaultTableCellRenderer renderer = new DefaultTableCellRenderer();
        renderer.setHorizontalAlignment(JLabel.CENTER);
        table.setDefaultRenderer(Object.class, renderer);

        table.getTableHeader().setReorderingAllowed(false);
        table.setPreferredScrollableViewportSize(new Dimension(800, 360));
        return new JScrollPane(table);
    }

    private void addTableMouseListener() {
        table.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                int row = table.rowAtPoint(e.getPoint());
                int column = table.columnAtPoint(e.getPoint());

                // 升序
                if (column == 4) {
                    if (row > 0) {
                        Language temp = tableModel.getLanguageAt(row);
                        List<Language> languageList = tableModel.getLanguageList();
                        languageList.set(row, languageList.get(row - 1));
                        languageList.set(row - 1, temp);
                        tableModel.setLanguageList(languageList);
                        tableModel.updateData();
                    }
                } else if (column == 5) {  // 降序
                    if (row < tableModel.getLanguageList().size() - 1) {
                        Language temp = tableModel.getLanguageAt(row);
                        List<Language> languageList = tableModel.getLanguageList();
                        languageList.set(row, languageList.get(row + 1));
                        languageList.set(row + 1, temp);
                        tableModel.setLanguageList(languageList);
                        tableModel.updateData();
                    }
                } else if (column == 6) {  // 删除
                    tableModel.deleteLanguage(row);
                    tableModel.updateData();
                }

            }
        });
    }

    public static void main(String[] args) {
        MainUI mainUI = new MainUI();
    }
}

